#define _CRT_SECURE_NO_WARNINGS 1
#include"Seqlist.h"

void SLInit(SL* ps)
{
	assert(ps);

	ps->array = NULL;
	ps->capicity = ps->size = 0;
}

void SLDestory(SL* ps)
{
	assert(ps);

	if (ps->array)
	{
		free(ps);
		ps->array = NULL;
		ps->capicity = ps->size = 0;
	}
}

void SLPrint(SL* ps)
{
	assert(ps);

	for(int i = 0;i < ps->size;i++)
	{
		printf("%d ", ps->array[i]);
	}
	printf("\n");
}

void SLCheckCapacity(SL* ps)
{
	assert(ps);
	if (ps->size == ps->capicity)
	{
		int Newcapicity = ps->capicity == 0 ? 4 : ps->capicity * 2;
		SLDataType* tmp = (SLDataType*)realloc(ps->array, sizeof(SLDataType) * Newcapicity);
		if (tmp)
		{
			perror("realloc fail");
			exit(-1);
		}
		ps->array = tmp;
		ps->capicity = Newcapicity;
	}

}

void SLPushBack(SL* ps, SLDataType x)
{
	SLInsert(ps, ps->size, x);
}

void SLPopBack(SL* ps)
{
	SLErase(ps, ps->size);
}

void SLPushFront(SL* ps, SLDataType x)
{
	SLInsert(ps, 0, x);
}

void SLPopFront(SL* ps, SLDataType x)
{
	SLErase(ps, 0);
}
void SLInsert(SL* ps, int pos, SLDataType x)
{
	assert(ps);
	assert(pos >= 0);
	assert(pos <= ps->size);

	SLCheckCapacity(ps);
	int end = ps->size - 1;
	while (end >= pos)
	{
		ps->array[end + 1] = ps->array[end];
	}
	ps->array[pos] = x;
	ps->size++;
}

void SLErase(SL* ps, int pos)
{
	assert(ps);
	assert(pos >= 0);
	assert(pos < ps->size);

	int begin = pos + 1;
	while (begin < ps->size)
	{
		ps->array[begin - 1] = ps->array[begin];
		begin++;
	}
	ps->size--;
}

void SLFind(SL* ps, SLDataType x, int begin)
{
	assert(ps);

	int i = begin;
	while (i < ps->size)
	{
		if (ps->array[i] == x)
		{
			return i;
		}
		i++;
	}
	return -1;
}